<template>
  <div class="app-container">
    <h3 style="font-weight: bold;">查询条件</h3>
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="20" :offset="1">
          <el-form-item label="文件编号" prop="f0901">
            <el-input v-model="queryParams.f0901" placeholder="请输入文件编号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="上传人" prop="f0909">
            <el-input v-model="queryParams.f0909" placeholder="请输入上传人" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="文件名称" prop="f0902">
            <el-input v-model="queryParams.f0902" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item id="query-button">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="20" :offset="1">
          <el-form-item label="文件格式" prop="f0904">
            <el-select v-model="queryParams.f0904" placeholder="请选择文件格式" clearable>
              <el-option v-for="dict in dict.type.client_document_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="上传时间">
            <el-date-picker v-model="daterangeF0905" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form> -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="16" :offset="1">
          <el-form-item label="上传人" prop="f2102">
            <el-input v-model="queryParams.f2102" placeholder="请输入上传人" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="版本号" prop="f2105">
            <el-input v-model="queryParams.f2105" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="是否启用" prop="delFlag">
            <el-select v-model="queryParams.delFlag" clearable @keyup.enter.native="handleQuery" placeholder="请选择">
              <el-option label="是" :value="0"></el-option>
              <el-option label="否" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态" prop="f2108">
            <el-select v-model="queryParams.f2108" clearable @keyup.enter.native="handleQuery" placeholder="请选择">
              <el-option label="已通过" :value="0"></el-option>
              <el-option label="未通过" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item id="query-button">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleAddVersion">新增版本</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['knowledge_manage:T09:add']">上传文件</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['knowledge_manage:T09:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- <el-table v-loading="loading" :data="T09List" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件编号" align="center" prop="f0901" />
      <el-table-column label="上传人" align="center" prop="f0909" />
      <el-table-column label="文件名称" align="center" prop="f0902" />
      <el-table-column label="文件格式" align="center" prop="f0904">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.client_document_type" :value="scope.row.f0904"/>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="f0905" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.F0905, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['knowledge_manage:T09:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['knowledge_manage:T09:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->

    <el-table v-loading="loading" :data="T09List" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上传人" align="center" prop="f2102" />
      <el-table-column label="版本号" align="center" prop="f2105" />
      <el-table-column label="是否启用" align="center" prop="delFlag">
        <template slot-scope="scope">
          <el-tag :type="scope.row.delFlag === '0' ? 'success' : 'danger'">{{ scope.row.delFlag === '0' ? '是' :
            '否'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateDate" width="180" />
      <el-table-column label="审批状态" align="center" prop="f2108">
        <template slot-scope="scope">
          <el-tag :type="scope.row.f2108 === 0 ? 'success' : 'danger'">{{ scope.row.f2108 === 0 ? '已通过' :
            '未通过'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleChange(scope.row)">切换版本</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改知识库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-upload class="upload-demo" ref="upload" action="#" :before-upload="beforeUpload"
          :on-change="handleFileChange" multiple :auto-upload="false" :limit="10" :on-exceed="handleExceed"
          :accept="fileType" :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf/png/jpg/xlsx文件，且不超过1万字</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  #query-button{
    min-width: 160px;
  }
</style>

<script>
import { listT09, getT09, delT09, addT09, updateT09, listT09History } from "@/api/knowledge_manage/T09";

export default {
  name: "Knowledge",
  dicts: ['client_document_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识库管理表格数据
      T09List: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文件字数时间范围
      daterangeF0905: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        f0901: null,
        f0909: null,
        f0902: null,
        f0904: null,
        f0905: null,
        f2102: null,
        f2105: null,
        f2108: null,
        delFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      fileList: [], // 用于存储上传的文件列表
      // 上传文件类型
      fileType:".doc,.docx,.pdf,.png,.jpg,.xlsx"
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询知识库管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeF0905 && '' != this.daterangeF0905) {
        this.queryParams.params["beginF0905"] = this.daterangeF0905[0];
        this.queryParams.params["endF0905"] = this.daterangeF0905[1];
      }
      // listT09(this.queryParams).then(response => {
      //   this.T09List = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
      listT09History(this.queryParams).then(response => {
        this.T09List = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
    },
    // 表单重置
    reset() {
      this.form = {
        f0901: null,
        f0601: null,
        f0301: null,
        f0902: null,
        f0903: null,
        f0904: null,
        f0905: null,
        f0906: null,
        f0907: null,
        f0909: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeF0905 = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.F0901)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 切换版本按钮
    handleChange(row) {
      this.$router.push(`/Knowledge/version/${row.f2107}`)
    },
    // 新增版本
    handleAddVersion() {
      this.$router.push(`/Knowledge/version/0`)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加知识库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const f0901 = row.f0901 || this.ids
      getT09(f0901).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改知识库管理";
      });
    },
    /** 提交按钮 */
     submitForm() {
      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      //     // 表单验证通过，可以进行文件上传
      //     this.uploadFiles();
      //   } else {
      //     console.log('表单验证失败');
      //     return false;
      //   }
      // });
      this.uploadFiles();
      this.open = false;
    },
    //文件上传
    uploadFiles() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择要上传的文件');
        return;
      }

      const formData = new FormData();

      // 遍历文件列表，将每个文件添加到FormData中
      this.fileList.forEach((file, index) => {
        // 使用files[]数组形式传递多个文件
        formData.append('files', file.raw);

        // 可以添加额外的文件信息
        formData.append(`fileInfo[${index}].name`, file.name);
        formData.append(`fileInfo[${index}].type`, file.raw.type);
      });

      // 添加其他表单数据（如果需要）
      if (this.form.f0901) {
        formData.append('f0901', this.form.f0901);
      }

      // 打印FormData内容以便调试
      console.log('FormData内容:');
      for (let [key, value] of formData.entries()) {
        console.log(key, value);
      }

      // 发送请求
      addT09(formData)
        .then(response => {
          this.$message.success('文件上传成功');
          this.open = false;
          this.getList();
          this.fileList = [];
        })
        .catch(error => {
          console.error('上传错误:', error);
          this.$message.error('文件上传失败');
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const F0901s = row.F0901 || this.ids;
      this.$modal.confirm('是否确认删除知识库管理编号为"' + F0901s + '"的数据项？').then(function() {
        return delT09(F0901s);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('knowledge_manage/T09/export', {
        ...this.queryParams
      }, `T09_${new Date().getTime()}.xlsx`)
    },
    // 文件上传函数
    handleFileChange(file, fileList) {
      console.log("文件改变",file, fileList);
      if (!file.raw && file.raw !== file) {
        // 如果raw不存在，将原始File对象赋值给raw
        file.raw = file;
      }

      this.fileList = fileList.map(item => {
        // 确保每个文件都有raw属性
        if (!item.raw && item.raw !== item) {
          item.raw = item;
        }
        return item;
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件`);
    },
    beforeUpload(file){
      const fileExtension = file.name.split('.').pop().toLowerCase();
      console.log("文件扩展名", fileExtension);

      if (!this.fileType.includes(`.${fileExtension}`)) {
        this.$message.error('仅允许上传 .doc,.docx,.pdf,.png,.jpg,.xlsx文件！');
        return Promise.reject();
      }

      // 确保file.raw存在
      if (!file.raw) {
        file.raw = file;
      }

      return false; // 阻止自动上传
    }
  }
};
</script>
